<?php
/**
 * Author: jikeSen
 * Email: 569045356@qq.com
 * WeChat: coco44886660
 * Date: 2018/4/10
 * Time: 下午2:25
 */

namespace app\open\controller;

use app\common\ShaoHuoPay\Pay;
use app\api\service\JpushService;
use app\common\Model\Order;

class Alipayvt
{
    protected $config;

    public function __construct()
    {
        unset($_REQUEST['s']);
        $this->config = [
            'app_id' => config('pay')['ALI_PAY_V2']['APPID'],
            'notify_url' => config('pay')['ALI_PAY_V2']['notify_url'],
            'return_url' => '',//config('pay')['ALI_PAY']['return_url'],
            'ali_public_key' => config('pay')['ALI_PAY_V2']['ali_public_key'],
            'private_key' => config('pay')['ALI_PAY_V2']['ali_private_key'],
        ];
    }

    public function notifyvt()
    {
        $alipay = Pay::alipay($this->config);

        try {
            //签名验证
            $data = $alipay->verify();

            //阿里回调的参数
            $params = $data->all();
            WLog('ali_params.txt',json_encode($params));
            $order_num = $params['out_trade_no'];//商户订单号
            $trade_status = $params['trade_status'];//交易状态

            if ($trade_status != 'TRADE_FINISHED' && $trade_status != 'TRADE_SUCCESS') {
                //支付交易状态不对
                return false;
            }
            $sys_orderinfo = Order::getOrderInfoByOrderNumOrId($order_num, '');

            if ($sys_orderinfo['code'] == 'success' && $sys_orderinfo['data']['order_type'] == 1) {
                //极光推送订单
                JpushService::instance()->makeOrder($sys_orderinfo['data']['order_id']);
                $res = Order::updateShaoHuoOrder($sys_orderinfo['data']['uid'], $params['out_trade_no'], $sys_orderinfo['data']['order_id'], $params['trade_no']);
                if ($res['code'] == 'success') {
                    return true;
                }
                return false;
            }
            //更新充值流水等
            if ($sys_orderinfo['code'] == 'success' && $sys_orderinfo['data']['order_type'] == 4) {//充值
                $res = Order::updateRechargeOrder($sys_orderinfo['data']['uid'], $params['out_trade_no'], $params['trade_no'], $sys_orderinfo['data']['amount']);
                if ($res['code'] == 'success') {
                    return true;
                }
                return false;
            }

        } catch (\Exception $e) {
            WLog('ali_no.txt', json_encode($_REQUEST));
            return false;
        }
    }
}